using System.Collections;
using UnityEngine;

namespace VoxelGame.NPC
{
	public class Interact : NPCBehaviour
	{
		[SerializeField]
		private string _tagTarget;

		[SerializeField]
		private string[] _interactAnimation;

		[SerializeField]
		private AudioClip[] _sound;

		[SerializeField]
		private float _soundDelay;

		[SerializeField]
		private GameObject _particleFeedback;

		private Transform _target;

		private Quaternion _targetRotation;

		private float _speed;

		private void Start()
		{
			GameObject gameObject = GameObject.FindWithTag(_tagTarget);
			if (gameObject != null)
			{
				_target = gameObject.transform;
			}
			else
			{
				UnityEngine.Debug.LogError("[" + base.gameObject.name + "] There is no target with the following tag: " + _tagTarget);
			}
		}

		private void OnEnable()
		{
			PlayParticle();
			PlayAnimation(RandomElement(_interactAnimation));
			StartCoroutine(InteractionTime());
		}

		private bool HasSound()
		{
			return _sound != null && _sound.Length > 1;
		}

		private void PlayParticle()
		{
			if (_particleFeedback != null)
			{
				_particleFeedback.SetActive(value: false);
				_particleFeedback.SetActive(value: true);
			}
		}

		private void PlaySound()
		{
			_npcControls.PlaySound(RandomElement(_sound));
		}

		private IEnumerator InteractionTime()
		{
			yield return new WaitForSeconds(_soundDelay);
			if (_sound != null && _sound.Length >= 1)
			{
				PlaySound();
			}
			yield return new WaitForSeconds(_minDuration);
			_npcControls.OnBehaviourFinished(this);
		}

		private void Update()
		{
			UpdateHeading();
		}

		private void UpdateHeading()
		{
			Vector3 forward = _target.position - base.transform.position;
			_targetRotation = Quaternion.LookRotation(forward, Vector3.up);
			Vector3 eulerAngles = _targetRotation.eulerAngles;
			_targetRotation = Quaternion.AngleAxis(eulerAngles.y, Vector3.up);
			base.transform.rotation = Quaternion.Slerp(base.transform.rotation, _targetRotation, Time.deltaTime * 5f);
		}
	}
}
